package com.zx.练习题._2022面试题收集;

import java.util.concurrent.LinkedBlockingQueue;
import lombok.extern.slf4j.Slf4j;

/**
 * 生产者消费者模型
 */
@Slf4j
public class Demo3 {

    public static void main(String[] args) {
        // 一个线程生产
        // 一个线程消费
        // 使用队列进行通讯
        LinkedBlockingQueue<Integer> queue = new LinkedBlockingQueue<>(500);
        new Thread(() -> {
            for (int i = 0; i < 10000; i++) {
                log.info("生产, i={}", i);
                queue.offer(i);
                try {
                    Thread.sleep(1000L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    break;
                }
            }
        }, "thread-producer").start();

        new Thread(() -> {
            for (; ; ) {
                try {
                    Integer take = queue.take();
                    log.info("消费1, i={}", take);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    break;
                }
            }
        }, "thread-consumer1").start();


    }
}
